// src/services/storage.ts
import { supabase } from '@/lib/supabase'

/**
 * 上传图片到 Supabase Storage
 * @param filePath 小程序/App 的临时文件路径
 * @param bucketName 存储桶名称，默认为 'images'
 * @returns 返回公开的图片 URL
 */
export const storageService = {
  async uploadImage(filePath: string, bucketName: string = 'images'): Promise<string> {
    try {
      // 1. 从完整路径中提取文件名
      const fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
      // 2. 创建一个更独特的文件名，防止冲突
      const uniqueFileName = `${Date.now()}-${fileName}`

      // 3. 上传文件
      const { data, error: uploadError } = await supabase.storage
        .from(bucketName)
        .upload(uniqueFileName, filePath, {
          cacheControl: '3600',
          upsert: false,
        })

      if (uploadError) {
        console.error('Upload error:', uploadError)
        throw new Error(`图片上传失败: ${uploadError.message}`)
      }

      // 4. 获取上传后文件的公开 URL
      const { data: publicUrlData } = supabase.storage
        .from(bucketName)
        .getPublicUrl(data.path)

      if (!publicUrlData || !publicUrlData.publicUrl) {
        throw new Error('获取图片公开链接失败')
      }

      return publicUrlData.publicUrl
    }
    catch (err) {
      console.error('An unexpected error occurred in uploadImage:', err)
      // @ts-ignore
      throw new Error(err.message || '图片上传时发生未知错误')
    }
  },
  async uploadImage2(filePath: string, bucketName: string = 'moments'): Promise<string> {
    try {
      // 1. 从完整路径中提取文件名
      const fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
      // 2. 创建一个更独特的文件名，防止冲突
      const uniqueFileName = `${Date.now()}-${fileName}`

      // 3. 上传文件
      const { data, error: uploadError } = await supabase.storage
        .from(bucketName)
        .upload(uniqueFileName, filePath, {
          cacheControl: '3600',
          upsert: false,
        })

      if (uploadError) {
        console.error('Upload error:', uploadError)
        throw new Error(`图片上传失败: ${uploadError.message}`)
      }

      // 4. 获取上传后文件的公开 URL
      const { data: publicUrlData } = supabase.storage
        .from(bucketName)
        .getPublicUrl(data.path)

      if (!publicUrlData || !publicUrlData.publicUrl) {
        throw new Error('获取图片公开链接失败')
      }

      return publicUrlData.publicUrl
    }
    catch (err) {
      console.error('An unexpected error occurred in uploadImage:', err)
      // @ts-ignore
      throw new Error(err.message || '图片上传时发生未知错误')
    }
  },
}
